package com.fjnu.service.impl;

import com.fjnu.common.ArticleConstants;
import com.fjnu.dao.ArticleDao;
import com.fjnu.dao.UserDao;
import com.fjnu.domain.dto.ArticleUpdateDto;
import com.fjnu.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao ;
    @Autowired
    private UserDao userDao ;

    @Override
    public int updateArticle(ArticleUpdateDto articleUpdateDto) {
        /**
         * 1. 先检查是否存在该文章
         * 2. 根据DTO来更新文件
         * 3. 返回更新结果
         */
        return 0;
    }

    @Transactional(

            propagation = Propagation.REQUIRED,
            isolation = Isolation.READ_COMMITTED,
            timeout = -1,
            rollbackFor = {Exception.class},
            readOnly = false

    )
    @Override
    public int publishArticle(Integer articleId, Integer userId) {
        /**
         *
         * 1. 检查文章是否已经发布
         * 2. 更新文章状态为已发布
         * 3. 更新作者的积分
         * 4. 返回更新结果
         **/
        if (articleId == null || userId == null) {
            return 0 ;
        }

        if (articleDao.selectById(articleId) == null){
            return 0 ;
        }

        int retUpdateStatus = articleDao.updateStatus(articleId,
                ArticleConstants.ARTICLE_PUBLISHED) ;

        int retUpdateScore = userDao.updateScore(userId, ArticleConstants.SCORE_PUBLISH_ARTICLE) ;


        return retUpdateScore + retUpdateStatus == 2 ? 1 : 0;
    }

}
